package com.dawn.module.hospital.controller.app.pub;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.util.json.JsonUtils;
import com.dawn.framework.web.core.util.RequestUtils;
import com.dawn.module.hospital.controller.app.base.BaseController;
import com.dawn.module.hospital.controller.app.inhospital.vo.InHospitalQueryReqVO;
import com.dawn.module.hospital.controller.app.pub.vo.PatientInfoReqVO;
import com.dawn.module.hospital.controller.app.pub.vo.PatientVisitReqVO;
import com.dawn.module.hospital.controller.app.pub.vo.WxAccessTokenReqVO;
import com.dawn.module.hospital.controller.app.register.vo.RegisterQueryReqVO;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.service.InHospitalService;
import com.dawn.module.hospital.service.PatientService;
import com.dawn.module.hospital.service.RegisterService;
import com.dawn.module.mp.api.accessToken.AccessTokenApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2025/9/22 15:20
 */
@Tag(name = "公用 第三方APP - bh")
@RestController
@RequestMapping("/bh/api")
@Validated
@Slf4j
public class AppPubThirdController extends BaseController {


    @Value("${local.api.username}")
    protected String username;

    @Value("${local.api.password}")
    protected String password;

    @Resource
    private AccessTokenApi accessTokenApi;

    @Resource
    private PatientService patientService;

    @Resource
    private RegisterService registerService;

    @Resource
    private InHospitalService inHospitalService;

    @RequestMapping(value = "/token")
    @Operation(summary = "获取微信access_token")
    @PermitAll
    public CommonResult token(HttpServletRequest request) {
        log.info("---------获取微信access_token token begin...-------");
        JSONObject json = RequestUtils.getReqParamJSON(request);
        log.warn("---------token 获取微信access_token:"+ json.toJSONString());
        if(json.isEmpty()){
            Map param = parseRequestParamMap(request, false);
            log.warn("--------token 获取微信access_token-------Map:"+ JsonUtils.toJsonString(param));
            json = JsonUtils.parseObject(JsonUtils.toJsonString(param),JSONObject.class);
        }

        WxAccessTokenReqVO wxAccessTokenReqVO = JsonUtils.parseObject(JsonUtils.toJsonString(json),WxAccessTokenReqVO.class);


        if(!username.equals(wxAccessTokenReqVO.getUserName()) ||
                !password.equals(wxAccessTokenReqVO.getPassword()) ) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),"请检查接口用户信息");
        }

        CommonResult commonResult = accessTokenApi.getAccessToken(wxAccessTokenReqVO.getAppId());

        if (!CommonResult.isSuccess(commonResult.getCode())) {
            return commonResult;
        }

        Map map = new HashMap();
        map.put("wxAccessToken",String.valueOf(commonResult.getData()));
        return CommonResult.success(map);
    }


    @RequestMapping(value = "/patient")
    @Operation(summary = "获取患者信息")
    @PermitAll
    public CommonResult patientInfo(HttpServletRequest request) {
        log.info("---------获取患者信息 begin...-------");
        JSONObject json = RequestUtils.getReqParamJSON(request);
        log.warn("---------获取患者信息:"+ json.toJSONString());
        if(json.isEmpty()){
            Map param = parseRequestParamMap(request, false);
            log.warn("--------获取患者信息-------Map:"+ JsonUtils.toJsonString(param));
            json = JsonUtils.parseObject(JsonUtils.toJsonString(param),JSONObject.class);
        }

        PatientInfoReqVO patientInfoReqVO = JsonUtils.parseObject(JsonUtils.toJsonString(json),PatientInfoReqVO.class);


        if(!username.equals(patientInfoReqVO.getUserName()) ||
                !password.equals(patientInfoReqVO.getPassword()) ) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),"请检查接口用户信息");
        }

        CommonResult httpResult = patientService.findPatientByOpenId(patientInfoReqVO.getOpenId());
        if(httpResult.isError()) {
            return httpResult;
        }

        List<Map> list = new ArrayList<>();

        JSONArray jsonArray = (JSONArray)httpResult.getData();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Map p = new HashMap();
            p.put("openid", jsonObject.get("openid"));
            p.put("province", jsonObject.get("province"));
            p.put("city", jsonObject.get("city"));
            p.put("county", jsonObject.get("county"));
            p.put("name", jsonObject.get("name"));
            p.put("patientId", jsonObject.get("patientId"));
            p.put("patientSex", jsonObject.get("patientSex"));
            p.put("birthday", jsonObject.get("birthday"));
            p.put("patientAge", jsonObject.get("patientAge"));
            p.put("cardNo", jsonObject.get("cardNo"));
            p.put("phone", jsonObject.get("phone"));
            p.put("address", jsonObject.get("address"));
            p.put("nation",jsonObject.get("nation"));
            list.add(p);
        }

        if(list.size() > 0){
            return CommonResult.success(list);
        } else {
            return CommonResult.error(GlobalErrorCodeConstants.UNKNOWN.getCode(),"未查找到数据");
        }

    }

    @RequestMapping(value = "/patient/visit")
    @Operation(summary = "获取患者就诊信息")
    @PermitAll
    public CommonResult visitInfo(HttpServletRequest request) {
        log.info("---------获取患者就诊信息 begin...-------");
        JSONObject json = RequestUtils.getReqParamJSON(request);
        log.warn("---------获取患者就诊信息:" + json.toJSONString());
        if (json.isEmpty()) {
            Map param = parseRequestParamMap(request, false);
            log.warn("--------获取患者就诊信息-------Map:" + JsonUtils.toJsonString(param));
            json = JsonUtils.parseObject(JsonUtils.toJsonString(param), JSONObject.class);
        }

        PatientVisitReqVO patientVisitReqVO = JsonUtils.parseObject(JsonUtils.toJsonString(json), PatientVisitReqVO.class);


        if (!username.equals(patientVisitReqVO.getUserName()) ||
                !password.equals(patientVisitReqVO.getPassword())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST.getCode(), "请检查接口用户信息");
        }


        RegisterQueryReqVO reqVO = new RegisterQueryReqVO();
        reqVO.setPatientId(patientVisitReqVO.getPatientId());
        CommonResult httpResult = registerService.seeRecord(reqVO);

        CommonResult result = null;
        Map resultMap = new HashMap();
        if (httpResult.isSuccess()) {
            resultMap.put("visitList",httpResult.getData());
            result = CommonResult.success(resultMap);
        }

        InHospitalQueryReqVO inHospitalReqVO = new InHospitalQueryReqVO();
        inHospitalReqVO.setInPatientId(patientVisitReqVO.getPatientId());
        inHospitalReqVO.setInPatientId("1");
        CommonResult inHospitalResult = inHospitalService.record(inHospitalReqVO);
        if (inHospitalResult.isSuccess()) {
            resultMap.put("inHospitalList",inHospitalResult.getData());
            result = CommonResult.success(resultMap);
        }


        String clinicNo = patientService.getClinicNoByPatientId(patientVisitReqVO.getPatientId());
        if(StringUtils.hasLength(clinicNo)) {
            resultMap.put("patientNo",clinicNo);
            result = CommonResult.success(resultMap);
        }

        return result;
    }


}
